695. 岛屿的最大面积
为保证权益,题目请参考 695. 岛屿的最大面积(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int ans = 0;
int maxAreaOfIsland(vector<vector<int>> &grid)
{
for (int i = 0; i < grid.size(); ++i)
{
for (int j = 0; j < grid[0].size(); ++j)
{
if (grid[i][j] == 1)
{
dfs(grid, i, j, 1);
}
}
}
return ans;
}
void dfs(vector<vector<int>> &grid, int i, int j, int len)
{
grid[i][j] = -1;
if (ans < len)
{
ans = len;
}
if (i - 1 >= 0)
dfs(grid, i - 1, j, len + 1);
if (i + 1 < grid.size())
dfs(grid, i + 1, j, len + 1);
if (j - 1 >= 0)
dfs(grid, i, j - 1, len + 1);
if (j + 1 < grid[0].size())
dfs(grid, i, j + 1, len + 1);
}
};
int main()
{
vector<vector<int>> vec;
vector<int> row1;
row1.push_back(1);
row1.push_back(1);
row1.push_back(0);
row1.push_back(0);
row1.push_back(0);
vec.push_back(row1);
vector<int>
row2;
row2.push_back(1);
row2.push_back(1);
row2.push_back(0);
row2.push_back(0);
row2.push_back(0);
vec.push_back(row2);
vector<int>
row3;
row3.push_back(0);
row3.push_back(0);
row3.push_back(0);
row3.push_back(1);
row3.push_back(1);
vec.push_back(row3);
vector<int> row4;
row4.push_back(0);
row4.push_back(0);
row4.push_back(0);
row4.push_back(1);
row4.push_back(1);
vec.push_back(row4);
Solution so;
cout << so.maxAreaOfIsland(vec) << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84